package cn.tianyigps.tianyigpskafka.task.util;

import cn.tianyigps.tianyigpskafka.task.bean.Task;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;

/**
 * Created with IDEA
 *
 * @description: 任务序列化与反序列化工具类
 * @author: cui.guibin
 * @create: 2019/3/18 9:36
 **/
@Slf4j
public class TaskUtil {

    private static final ObjectMapper OM = new ObjectMapper();

    private static final int ONE_M_LENGTH = 1000 * 1024;

    /**
     * @param: String message
     * @return  Task
     * @author cui.guibin
     * @date 2019/3/18 9:30
     * 反序列化json 成Task对象
     */
    public static Task json2Task(String message){

        Task task = new Task();
        if (StringUtils.isEmpty(message))
            return task;
        try {
            task = OM.readValue(message, Task.class);
        } catch (IOException e) {
            log.error("json解析失败 ：" + message);
            e.printStackTrace();
        }
        return task;
    }
    /**
     * @param: Task task
     * @return  String
     * @author cui.guibin
     * @date 2019/3/18 9:30
     * 序列化Task对象到json
     */
    public static String task2Json(Task task){

        String json = "";
        if (!Optional.ofNullable(task).isPresent())
            return json;
        try {
            json = OM.writeValueAsString(task);
        } catch (IOException e) {
            log.error("对象序列化失败 ： " + task);
            e.printStackTrace();
        }
        return json;
    }
    /**
     * @param: Task task
     * @return  String
     * @author cui.guibin
     * @date 2019/3/18 9:30
     * 检查数据大小
     */
    public static Boolean checkDataSize(Task task, Map<String, Object> map){

        String json = "";
        if (!Optional.ofNullable(task).isPresent())
            return false;
        try {
            json = OM.writeValueAsString(task);
        } catch (IOException e) {
            log.error("对象序列化失败 ： " + task);
            map.put("data2JsonErr","任务下发错误 ： " + task);
            e.printStackTrace();
        }
        if(!StringUtils.isEmpty(json)){
            byte[] bytes = json.getBytes();
            int length = bytes.length;
            if ( length> ONE_M_LENGTH){
                log.error("数据大于1M");
                map.put("dataSize","数据大于1M");
                return false;

            }
            return true;
        }
        return false;
    }

}
